package com.ys.erp.stage_marketing_service.config;

import com.alibaba.nacos.shaded.com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferManagerConfiguration;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * @author lwj
 * @date 2023/4/11
 */
@Configuration
@Getter
@Setter

public class TencentConfig {

    @Value("${properties.tencent.cos.secret-id}")
    private String secretId;

    @Value("${properties.tencent.cos.secret-key}")
    private String secretKey;

    @Value("${properties.tencent.cos.region}")
    private String region;

    @Bean
    public COSClient cosClient() {
        // 1 初始化用户身份信息
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        clientConfig.setConnectionTimeout(1000*60);
        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

    @Bean
    public TransferManager createTransferManager(@Qualifier("cosClient") COSClient cosClient,
                                                 @Qualifier("cosExecutor") ExecutorService executorService) {
        // 自定义线程池大小，建议在客户端与 COS 网络充足（例如使用腾讯云的 CVM，同地域上传 COS）的情况下，设置成16或32即可，可较充分的利用网络资源
        TransferManager transferManager = new TransferManager(cosClient, executorService);
        // 设置高级接口的配置项
        // 分块上传阈值和分块大小分别为 5MB 和 1MB
        TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
        transferManagerConfiguration.setMultipartUploadThreshold(5 * 1024 * 1024);
        transferManagerConfiguration.setMinimumUploadPartSize(1024 * 1024);
        transferManager.setConfiguration(transferManagerConfiguration);
        return transferManager;
    }


    @Bean("cosExecutor")
    public ExecutorService cosExecutorService() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("cos-thread-").build();
        return new ThreadPoolExecutor(16, 32,
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), namedThreadFactory, new ThreadPoolExecutor.DiscardOldestPolicy());
    }



}
